//
//  SettlementViewController.m
//  ChunLaiZhuangClient
//
//  Created by xielihui on 16/3/11.
//  Copyright © 2016年 CLZ. All rights reserved.
//

#import "SettlementViewController.h"
#import "ReceiptAddressViewController.h"
#import "CouponListViewController.h"
#import "PayListViewController.h"
#import "CouponListModel.h"
#import "AddressListModel.h"
#import "CheckoutModel.h"
#import "PayModel.h"
#import <AlipaySDK/AlipaySDK.h>

#define SETTLEMENT_VIEW_HEIGHT 431.f

@interface SettlementViewController ()
@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIView *settlementContainer;
@property (weak, nonatomic) IBOutlet UIButton *closeBtn;
@property (weak, nonatomic) IBOutlet UIView *setttlementView;
@property (weak, nonatomic) IBOutlet UILabel *addressOwnerLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressDetailLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressTipLabel;
@property (weak, nonatomic) IBOutlet UILabel *addressLabel;
@property (weak, nonatomic) IBOutlet UILabel *couponNameLabel;

@property (weak, nonatomic) IBOutlet UILabel *shijiePriceLabel;
@property (weak, nonatomic) IBOutlet UIView *addressView;
@property (weak, nonatomic) IBOutlet UIView *couponView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraint1;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *constraint3;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *payViewConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *addressViewHeightConstraint;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *settlementViewContainerHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *couponViewConstraint;
@property (weak, nonatomic) IBOutlet UILabel *transPriceLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;
@property (weak, nonatomic) IBOutlet UIImageView *paymentImageView;
@property (weak, nonatomic) IBOutlet UIButton *settlementBtn;
@property (weak, nonatomic) IBOutlet UILabel *payMethodLabel;


@property (nonatomic, strong) ReceiptAddressViewController *receiptAddressVC;
@property (nonatomic, strong) CouponListViewController *couponListVC;
@property (nonatomic, strong) PayListViewController *payListVC;
@property(nonatomic, copy) NSString *totalPrice; //应付总额
@property(nonatomic, copy) NSString *transPrice;
@property(nonatomic,copy)NSString *shijiPrice;//实际支付
@property(nonatomic, strong) SimpleAddressModel *selectAddressModel;
@property(nonatomic, strong) SimpleCouponModel *selectCouponModel;
@property(nonatomic, strong) CheckoutModel *checkoutModel;
@property(nonatomic, strong) PaymentMethodModel *payModel;
@property(nonatomic, assign) BOOL isFromPurchasePage;
@property (weak, nonatomic) IBOutlet UILabel *youhuiLbael;
@end

@implementation SettlementViewController

- (id)initWithTransPrice:(NSString *)transPrice andTotalPrice:(NSString *)totalPrice {
    if (self = [super init]) {
        self.totalPrice = totalPrice;
        self.transPrice = transPrice;
    }
    return self;
}

- (void)setPurchaseParams:(NSMutableDictionary *)purchaseParams {
    _purchaseParams = purchaseParams;
    self.isFromPurchasePage = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.topView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(closeSettlementAction:)]];
    self.settlementBtn.layer.cornerRadius = 24.f;
    [self addChildViewController:self.receiptAddressVC];
    [self.view addSubview:self.receiptAddressVC.view];
    [self.view addSubview:self.couponListVC.view];
    [self.view addSubview:self.payListVC.view];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(onAliPayDoneNotification:)
                                                 name:@"AliPayNotification"
                                               object:nil];
    NSLog(@"self.settlementViewheight:%lf", self.settlementContainer.height);
    // Do any additional setup after loading the view from its nib.
}

- (void)getCheckoutInfos {
    if (self.isFromPurchasePage) {
        [ApiClient purchaseProduct:self.purchaseParams didFinishLoaded:^(CheckoutModel *model, NSString *path) {
            if ([model.status isEqual:@(1)]) {
                self.checkoutModel = model;
                self.payModel = model.data.payment_method;
                self.selectAddressModel = model.data.shipping_address;
                self.selectCouponModel = model.data.coupon;
                self.payListVC.paymentListArray = [NSMutableArray arrayWithArray:model.data.payment_methods];
                self.totalPrice=self.checkoutModel.data.subtotal;
                self.shijiPrice=self.checkoutModel.data.total;
                self.transPrice = self.checkoutModel.data.shipping_method.cost;
                NSString *yingfu=[self.checkoutModel.data.subtotal substringFromIndex:1];
                NSString *shiji=[self.checkoutModel.data.total substringFromIndex:1];
                self.youhuiLbael.text=[NSString stringWithFormat:@"%f",[yingfu doubleValue]-[shiji doubleValue]];
                [self updateViewLayout];
            } else {
                [self closeSettlementAction:nil];
            }
        } didFailLoaded:^(NSError *error, NSString *path) {
            
        }];
    } else {
        [ApiClient getCheckoutInfoDidFinishLoaded:^(CheckoutModel *model, NSString *path) {
            if ([model.status isEqual:@(1)]) {
                self.checkoutModel = model;
                self.payModel = model.data.payment_method;
                self.selectAddressModel = model.data.shipping_address;
                self.selectCouponModel = model.data.coupon;
                self.payListVC.paymentListArray = [NSMutableArray arrayWithArray:model.data.payment_methods];
                self.totalPrice=self.checkoutModel.data.subtotal;
                self.shijiPrice=self.checkoutModel.data.total;
                self.transPrice = self.checkoutModel.data.shipping_method.cost;
                NSString *yingfu=[self.checkoutModel.data.subtotal substringFromIndex:1];
                NSString *shiji=[self.checkoutModel.data.total substringFromIndex:1];
                self.youhuiLbael.text=[NSString stringWithFormat:@"￥%.2f",[yingfu doubleValue]-[shiji doubleValue]];
                [self updateViewLayout];
            } else {
                [self closeSettlementAction:nil];
            }
        } didFailLoaded:^(NSError *error, NSString *path) {
            
        }];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:NO];
}

- (void)setNeedGoBack:(BOOL)needGoBack {
    _needGoBack = needGoBack;
}

- (ReceiptAddressViewController *)receiptAddressVC {
    if (!_receiptAddressVC) {
        _receiptAddressVC = [[ReceiptAddressViewController alloc] init];
        _receiptAddressVC.view.frame = self.view.frame;
        _receiptAddressVC.view.height = SETTLEMENT_VIEW_HEIGHT;
        _receiptAddressVC.view.top = 1000.f;
        __weak typeof(self) weakSelf = self;
        _receiptAddressVC.chooseReceiptAddressBlock = ^(AddressSubModel *model){
            [weakSelf getCheckoutInfos];
            weakSelf.selectAddressModel = [[SimpleAddressModel alloc] init];
            weakSelf.selectAddressModel.firstname = model.firstname;
            weakSelf.selectAddressModel.address = model.formatted_address;
            weakSelf.selectAddressModel.address_id = model.address_id;
            weakSelf.selectAddressModel.telephone = model.telephone;
            [weakSelf updateViewLayout];
        };
        _receiptAddressVC.closePageAction = ^() {
            [weakSelf closeAddressAction];
        };
    }
    return _receiptAddressVC;
}

- (CouponListViewController *)couponListVC {
    if (!_couponListVC) {
        _couponListVC = [[CouponListViewController alloc] init];
        _couponListVC.view.frame = self.view.frame;
        _couponListVC.view.height = SETTLEMENT_VIEW_HEIGHT;
        _couponListVC.view.top = 1000.f;
        __weak typeof(self) weakSelf = self;
        _couponListVC.closeCouponPageBlock = ^(){
            [weakSelf closeCouponAction];
        };
        _couponListVC.chooseCouponBlock = ^(CouponModel *model) {
            SimpleCouponModel *cModel = [[SimpleCouponModel alloc] init];
            [weakSelf getCheckoutInfos];
            cModel.code = model.code;
            cModel.name = model.name;
            weakSelf.selectCouponModel = cModel;
            [weakSelf updateViewLayout];
        };
    }
    return _couponListVC;
}

- (PayListViewController *)payListVC {
    if (!_payListVC) {
        _payListVC = [[PayListViewController alloc] init];
        _payListVC.view.frame = self.view.frame;
        _payListVC.view.height = SETTLEMENT_VIEW_HEIGHT;
        _payListVC.view.top = 1000.f;
        __weak typeof(self) weakSelf = self;
        _payListVC.closePayPageBlock = ^(){
            [weakSelf closePayPageAction];
        };
        _payListVC.selectPayMethodBlock = ^(PaymentMethodModel *payModel) {
            [weakSelf getCheckoutInfos];
            weakSelf.payModel = payModel;
            [weakSelf updateViewLayout];
        };
    }
    return _payListVC;
}

- (IBAction)closeSettlementAction:(id)sender {
    if ([self.delegate respondsToSelector:@selector(closeSettlementViewController:)]) {
        [self.delegate closeSettlementViewController:self];
    }
}

- (IBAction)chooseAddressAction:(id)sender {
    [self.receiptAddressVC.view setNeedsUpdateConstraints];
    [self.receiptAddressVC viewWillAppear:YES];
    self.constraint1.constant = 1000;
    self.constraint3.constant = -300;
    [UIView animateWithDuration:.3f animations:^{
        [self.view layoutIfNeeded];
        self.receiptAddressVC.view.top = self.view.height - self.settlementContainer.height;
    }];

}

- (void)updateViewLayout {
    if (self.selectAddressModel.firstname.length > 0) {
        self.addressLabel.text = @"";
        self.addressViewHeightConstraint.constant = 55.f;
        self.settlementViewContainerHeight.constant = SETTLEMENT_VIEW_HEIGHT + 55.f - 44.f;
        self.addressTipLabel.hidden = YES;
        self.addressOwnerLabel.text = [NSString stringWithFormat:@"%@ %@", self.selectAddressModel.firstname, self.selectAddressModel.telephone];
        self.addressDetailLabel.text = self.selectAddressModel.address;
        self.receiptAddressVC.view.height = SETTLEMENT_VIEW_HEIGHT + 55 - 44.f;
        self.couponListVC.view.height = SETTLEMENT_VIEW_HEIGHT + 55 - 44.f;
        self.payListVC.view.height = SETTLEMENT_VIEW_HEIGHT + 55 - 44.f;
    } else {
        self.receiptAddressVC.view.height = SETTLEMENT_VIEW_HEIGHT;
        self.couponListVC.view.height = SETTLEMENT_VIEW_HEIGHT;
        self.payListVC.view.height = SETTLEMENT_VIEW_HEIGHT;
        self.addressTipLabel.hidden = NO;
    }
    
    if (self.selectCouponModel) {
        self.couponNameLabel.hidden = NO;
        self.couponNameLabel.text = self.selectCouponModel.name;
        self.couponNameLabel.textColor=[UIColor colorWithHexString:@"8D8D8D"];
    } else {
        self.couponNameLabel.hidden = NO;
        if ([self.checkoutModel.data.available_coupons intValue]>0) {
             self.couponNameLabel.text=[NSString stringWithFormat:@"%@张可用",self.checkoutModel.data.available_coupons];
            self.couponNameLabel.textColor=[UIColor colorWithHexString:@"F35959"];
        }else{
          self.couponNameLabel.text=[NSString stringWithFormat:@"暂无优惠券可用"];
          self.couponNameLabel.textColor=[UIColor colorWithHexString:@"8D8D8D"];
        }
        
    }
    if (self.payModel) {
        [self.paymentImageView sd_setImageWithURL:[NSURL URLWithString:self.payModel.icon]];
        self.payMethodLabel.text = self.payModel.title;
        [self.payMethodLabel sizeToFit];
    }
    self.transPriceLabel.text = self.transPrice;
    self.totalPriceLabel.text = self.totalPrice;
    self.shijiePriceLabel.text=self.shijiPrice;
}

- (void)closeAddressAction {
    self.constraint1.constant = 0;
    self.constraint3.constant = 14.f;
    [UIView animateWithDuration:.3f animations:^{
        [self.view layoutIfNeeded];
        self.receiptAddressVC.view.top = self.view.height;
    }];
}

- (IBAction)chooseCouponAction:(id)sender {
    self.couponViewConstraint.constant = 1000;
    self.constraint3.constant = -300;
    [self.couponListVC viewWillAppear:YES];
    if (self.selectCouponModel) {
        self.couponListVC.couponCode=self.selectCouponModel.code;
    }else{
        self.couponListVC.couponCode=@"";
    }
    [UIView animateWithDuration:.3f animations:^{
        [self.view layoutIfNeeded];
        self.couponListVC.view.top = self.view.height - self.settlementContainer.height;
    }];
}

- (void)closeCouponAction {
    self.couponViewConstraint.constant = 0;
    self.constraint3.constant = 14.f;
    [UIView animateWithDuration:.3f animations:^{
        [self.view layoutIfNeeded];
        self.couponListVC.view.top = self.view.height;
    }];
}

- (IBAction)choosePayAction:(id)sender {
    self.payViewConstraint.constant = 1000;
    self.constraint3.constant = -300;
    [UIView animateWithDuration:.3f animations:^{
        [self.view layoutIfNeeded];
        self.payListVC.view.top = self.view.height - self.settlementContainer.height;
    }];
}

- (void)closePayPageAction {
    self.payViewConstraint.constant = 0;
    self.constraint3.constant = 14.f;
    [UIView animateWithDuration:.3f animations:^{
        [self.view layoutIfNeeded];
        self.payListVC.view.top = self.view.height;
    }];
}

- (IBAction)confirmOrderAction:(id)sender {
    [ApiClient confirmOrderDidFinishLoaded:^(PayModel *model, NSString *path) {
        if([model.status isEqual:@(1)]) {
            NSString *parms = model.data.payment_parameter;
            [[AlipaySDK defaultService] payOrder:parms fromScheme:@"alipay.chunlaizhuang" callback:^(NSDictionary *resultDic) {
                [self onAliPaymentResult:resultDic];
            }];
        }
    } didFailLoaded:^(NSError *error, NSString *path) {
        
    }];
}

//9000 支付成功，8000 正在处理， 4000 支付失败， 6001 中途取消，6002 网络连接出错
- (void)onAliPaymentResult:(NSDictionary *)resultDic {
    NSInteger statusCode = [resultDic[@"resultStatus"] integerValue];
    if (statusCode == 9000) {
        [[LKDHud shareHud] showtip:@"支付成功"];
    } else {
        [[LKDHud shareHud] showtip:@"支付不成功"];
    }
    if ([self.delegate respondsToSelector:@selector(payEndAction:)]) {
        [self.delegate payEndAction:self];
    }
}


- (void)onAliPayDoneNotification:(NSNotification *)notification {
    //self
    NSInteger statusCode = [notification.object[@"resultStatus"] integerValue];
    if (statusCode == 9000) {
        [[LKDHud shareHud] showtip:@"支付成功"];
    } else {
        [[LKDHud shareHud] showtip:@"支付不成功"];
    }
    [self closeSettlementAction:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
